package com.ehotting.eaf.netty.action;

import com.ehotting.eaf.netty.domain.DataAble;

import com.ehotting.eaf.core.utils.SpringUtils;
import com.ehotting.eaf.core.utils.clazz.ClassScanHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NettyActionFactory implements InitializingBean {

	private final Logger logger = LoggerFactory.getLogger(NettyActionFactory.class);

	private final Map<String, ActionAble<DataAble>> messageActionMap = new HashMap<String, ActionAble<DataAble>>();

	protected String scanPackage;

	public ActionAble<DataAble> getAction(String action) {
		return messageActionMap.get(action);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void afterPropertiesSet() {
		logger.info("***************** Start scan package:"+scanPackage+" *****************");
		List<Class<?>> list = ClassScanHelper.getClassList(scanPackage, true , Action.class,null);

		for (Class<?> clazz : list) {
			Assert.notNull(clazz, "Type to check against must not be null");
			if (!ActionAble.class.isAssignableFrom(clazz)) {
				throw new RuntimeException(clazz.getSimpleName()	+ " is not assign ActionAble.");
			}
			Action actionType = clazz.getAnnotation(Action.class);
			if (actionType != null) {
				logger.info("Add class:{},key:{}",clazz,actionType.value());
				ActionAble<DataAble> action = (ActionAble<DataAble>) SpringUtils.getBean(clazz);
				Assert.isTrue(!messageActionMap.containsKey(actionType.value()),
						"messageActionMap["+actionType.value()+"] has contains "+messageActionMap.get(actionType.value())+".");
				messageActionMap.put(actionType.value(), action);
			}
		}
		logger.info("*********************** Finish scan package."+"*************************");
	}

	
	public void setScanPackage(String scanPackage) {
		this.scanPackage = scanPackage;
	}
}